package com.heima.admin.gateway.filter;

import com.heima.admin.gateway.utills.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
// @Order(1)   全局过滤器可以有多个 给一个值() 越小越先执行
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getURI().getPath();
        if (url.contains("login/in")) {
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.NOT_FOUND);//校验
            return response.setComplete();
        }
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int verifyToken = AppJwtUtil.verifyToken(claims);
            if (verifyToken > 0) {
                log.error("token  is overdue ,url:{} ,claims:{}", url, claims);
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
//         String id = (String) claims.get("id");
            Integer id = claims.get("id", Integer.class);
            if (id == null) {
                log.error("id is null ,url:{} ,claims:{}", url, claims);
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            ServerHttpRequest httpRequest = request.mutate().
                    headers(httpHeaders -> {
                        httpHeaders.add("userId", String.valueOf(id));
                    }).build();
            exchange.mutate().request(httpRequest).build();

        } catch (Exception e) {
            e.printStackTrace();

            log.error("verifyToken is  error ,url:{} ", url);
            response.setStatusCode(HttpStatus.NOT_FOUND);//校验
            return response.setComplete();

        }
        return chain.filter(exchange);
    }

    /**
     * Get the order value of this object.
     * <p>Higher values are interpreted as lower priority. As a consequence,
     * the object with the lowest value has the highest priority (somewhat
     * analogous to Servlet {@code load-on-startup} values).
     * <p>Same order values will result in arbitrary sort positions for the
     * affected objects.
     *
     * @return the order value
     * @see #HIGHEST_PRECEDENCE
     * @see #LOWEST_PRECEDENCE
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
